package Laborum2.repository;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.*;

import javax.sql.DataSource;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import Laborum2.Basicas.*;

@Component
public class JdbcCargosRepository implements CargoRepository{
	List<Cargos> cg1 = new ArrayList <Cargos>();
	Cargos cargo = new Cargos();
	
	@Autowired
	private DataSource dataSource;
	

	@Override
	public Cargos obtenerCargoByNombre(String car) {
		
	      String sql = "SELECT * from Cargos where desCargo=? and estado=1" ;
			
			Connection conn = null;
			PreparedStatement ps = null;
			ResultSet rs = null;
			
			try {
				conn = dataSource.getConnection();
				ps = conn.prepareStatement(sql);
				ps.setString(1, car);
				rs = ps.executeQuery();

				while (rs.next()) {
               	 cargo.setIdCargo(rs.getInt("id"));
               	 cargo.setDesCargo(rs.getString("desCargo"));
				cg1.add(cargo);
				}
	           
			} catch (SQLException ex) {

			}
			closeConecction(rs, ps, conn);
					return cargo;

	}
	

	private void closeConecction(ResultSet rs, PreparedStatement ps,
			Connection conn) {

		if (rs != null) {
			try {
				// Close to prevent database cursor exhaustion
				rs.close();
			} catch (SQLException ex) {
			}
		}
		if (ps != null) {
			try {
				// Close to prevent database cursor exhaustion
				ps.close();
			} catch (SQLException ex) {
			}
		}
		if (conn != null) {
			try {
				// Close to prevent database connection exhaustion
				conn.close();
			} catch (SQLException ex) {
			}
		}

	}
}

